<script>
export default {
  name: "MainPageR",
  data() {
    return {
      loading: false,
      centerDialogVisible:false,
      fileList:[
        {
          name:'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }
      ],
      checkedTypes: [],
      typeOptions: [
        { label: '小技巧', value: '小技巧' },
        { label: '小知识', value: '小知识' },
        { label: '小趣事', value: '小趣事' },
        { label: '新手养宠', value: '新手养宠' },
        { label: '饮食与营养', value: '饮食与营养' },
        { label: '健康与医疗', value: '健康与医疗' },
      ],
      textarea:'',
      searchKeyword: '',
      form:{
        id:'',
        title:'',
        publisherNo:'',
        type:'',
        image:'',
        content:'',
        imageBytes: '',
        imageFile: null
      },
      rules:{
        title:[
          {required: true, message: '请输入标题', trigger: 'blur'},
          { min: 2, message: '最少 2 个字', trigger: 'blur' },
        ],
        content:[
          {required: true, message: '请输入内容', trigger: 'blur'},
          { min: 10, message: '最少 10 个字', trigger: 'blur' },
        ],
      },
      cards: [],
      carouselItems: [
        {
          image: 'https://images.pexels.com/photos/4492166/pexels-photo-4492166.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
          altText: 'Image 1',
        },
        {
          image: 'https://images.pexels.com/photos/17503504/pexels-photo-17503504.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
          altText: 'Image 2',
        },
        {
          image: 'https://images.pexels.com/photos/11117057/pexels-photo-11117057.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
          altText: 'Image 3',
        },
        {
          image: 'https://images.pexels.com/photos/14913190/pexels-photo-14913190.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
          altText: 'Image 4',
        },
      ],
      isShowBackTop: false
    }
  },
  computed: {
    user() {
      return this.$store.state.user; // 从 Vuex 获取用户信息
    },
    isAnyCardExpanded() {
      return this.cards.some((card) => card.expanded);
    },
  },
  mounted() {
    this.loadPosts()
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    this.cards.forEach(card => {
      if (card.blobUrl) {
        URL.revokeObjectURL(card.blobUrl);
      }
    });
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods:{
    closeAllCards() {
      this.cards.forEach((card) => {
        card.expanded = false;
      });
      document.body.style.overflow = 'auto';
    },
    handleSearch() {
      this.loadPosts();
    },
    add(){//打开表单
      if (!this.user) {
        this.$message.error('请先登录！');
      } else {
        this.centerDialogVisible = true;
        this.form = { // 重置表单
          title: '',
          publisherNo: this.user.no,
          types: '',
          imageFile: '',
          content: '',
        };
        this.fileList = []; // 清空文件列表
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },

    // 处理登录按钮点击
    toLogin() {
      // 这里可以跳转到登录页面
      this.$router.push("/LoginPage");
    },
    // 处理注册按钮点击
    toRegister() {
      // 这里可以跳转到注册页面
      this.$router.push("/RegisterPage");
    },
    handleAccountClick() {
      if (!this.user) {
        this.$message.error('请先登录！');
      } else {
        this.$router.push('/MyAccount');
      }
    },

    logout() {
      this.$axios.get("/user/logout")
          .then(() => {
            this.$store.dispatch('logout');
            sessionStorage.clear(); // 清除所有会话存储
            this.$router.push("/");
          })
          .catch(err => {
            this.$message.error('退出失败: ' + err.message);
          });
    },
    async loadPosts()
    {
      this.loading = true;
      try {
        const res =await this.$axios.post(
            this.$httpUrl + '/knowledge/listPage',
            {
              pageNum: 1,
              pageSize: 10,
              param:{ keywords: this.searchKeyword.trim() }
            });
        console.log('搜索参数:', { keyword: this.searchKeyword });
        console.log('调试信息-Cards响应数据:', res.data);
        if (res.data.code === 200) {
          this.cards = await Promise.all(res.data.data.map(async  k => {
            let imageUrl = '';
            try {
              if (k.id) {
                const imageRes = await this.$axios.get(
                    `${this.$httpUrl}/knowledge/image/${k.id}?t=${Date.now()}`,
                    { responseType:'blob' }
                );
                if (imageRes.data.size > 0) {
                  const blob = new Blob([imageRes.data], {
                    type: imageRes.headers['content-type'] || 'image/jpeg'
                  });
                  imageUrl = URL.createObjectURL(blob);
                  // 释放之前的 Blob URL
                  if (k.blobUrl) URL.revokeObjectURL(k.blobUrl);
                  k.blobUrl = imageUrl; // 存储当前 Blob URL
                }
              }
            }catch (error) {
              console.error('图片加载失败',error);
              imageUrl = 'https://img.zcool.cn/community/0156e65d0f3560a801205e4bcd4d39.png?x-oss-process=image/auto-orient,1/resize,m_lfit,w_1280,limit_1/sharpen,100/quality,q_100';
            }
            return{
              id: k.id,
              title: k.title,
              expanded:false,
              content: k.content,
              author: k.publisherNo,
              tags: k.type ? k.type.split(',') : [],
              /*likes: k.likes || 0,
              liked:false,*/
              image: imageUrl,
              createTime: this.formatTime(k.createTime),
              blobUrl: imageUrl
            };
          }));
          console.log('处理后的卡片数据:', this.cards);
        }
      } catch (error) {
        this.$message.error('数据加载失败');
      }
    }
,
    handleFileChange(file) {
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('文件大小不能超过2M！');
        return false;
      }
      if (!['image/jpeg', 'image/png'].includes(file.raw.type)) {
        this.$message.error('仅支持JPEG/PNG格式');
        return false;
      }
      this.form.imageFile = file.raw;
      return true;
    },
    //文件上传处理
    async submitForm() {
      try {
        if (!this.form.title?.trim()) {
          this.$message.error('标题不能为空');
          return;
        }
        if (!this.form.content?.trim()) {
          this.$message.error('内容不能为空');
          return;
        }
        const formData = new FormData();
        formData.append('title', this.form.title);
        formData.append('content', this.form.content);
        formData.append('publisherNo', this.user.no);
        formData.append('types', this.checkedTypes.join(','));
        if (this.form.imageFile) {
          formData.append('imageFile', this.form.imageFile);
        }

        const res = await this.$axios.post(
            this.$httpUrl + '/knowledge/save',
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }
        );

        if (res.data.code !== 200) {
          this.$message.error(res.data.msg || '操作失败');
          return;
        }
        this.centerDialogVisible = false;
        this.loadPosts();
        this.$message.success('发布成功');
      } catch (error) {
        const msg = error.response?.data?.msg || error.message;
        this.$message.error(`提交失败: ${msg}`);
      }
    },
    formatTime(time) {
      return new Date(time).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
    },
    /*标签随机颜色*/
    getRandomTagType() {
      const types = ['', 'success', 'info', 'warning', 'danger','primary'];
      return types[Math.floor(Math.random() * types.length)];
    },
    toggleCard(item) {
      // 关闭其他已展开卡片
      this.cards.forEach((c) => {
        if (c.id !== item.id) c.expanded = false;
      });

      // 切换当前卡片的展开状态
      item.expanded = !item.expanded;

      // 如果卡片展开，禁止页面滚动
      document.body.style.overflow = item.expanded ? 'hidden' : 'auto';
    },
    handleScroll() {
      // 当滚动超过 200px 时显示按钮
      this.isShowBackTop = window.pageYOffset > 200
    },
    truncateContent(content) {
      return content.length > 100 ? content.substring(0, 100) + '...' : content;
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth' // 平滑滚动
      })
    },
  },
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="container">
      <el-row>
        <!-- Logo -->
        <el-col :span="12"><div class="grid-content1 bg-purple logo">
          <span>logo</span>
        </div></el-col>
        <!-- 登录和注册按钮 -->
        <el-col :span="12">
          <div class="grid-content bg-purple-light">
            <!-- 已登录时显示用户名和退出按钮 -->
            <template v-if="user">
              <el-link :underline="false" style="margin-right: 5px">
                欢迎, {{ user.name }}
              </el-link>
              <el-link :underline="false" @click.native="logout" style="margin-right: 50px">
                退出
              </el-link>
            </template>
            <!-- 未登录时显示登录和注册按钮 -->
            <template v-else>
              <el-link :underline="false" @click.native="toLogin" style="margin-right: 5px">
                登录
              </el-link>
              <el-link :underline="false" @click.native="toRegister" style="margin-right: 50px">
                注册
              </el-link>
            </template>
            <router-view></router-view>
          </div>
        </el-col>
      </el-row>
      <el-carousel class="carousel-container" autoplay>
        <div class="el-carousel__container">
          <el-carousel-item class="el-carousel-item" v-for="(item, index) in carouselItems" :key="index" >
            <img :src="item.image" :alt="item.altText" class="carousel-image" />
          </el-carousel-item>
        </div>
      </el-carousel>
      <!-- 导航栏 -->
      <nav class="nav">
         <el-link>
           <router-link class="nav_font" :to="{ hash:'#K_module' }">
             <div>Tips</div>
             <div>养宠分享</div>
           </router-link>
         </el-link>
        <el-link>
          <router-link to="/AdoptionPage">
            <div>Furever & Family</div>
            <div>带Ta回家</div>
          </router-link>
        </el-link>
        <el-link>
          <router-link to="/PetSearch">
            <div>ReunitePets</div>
            <div>寻宠</div>
          </router-link>
        </el-link>
        <el-link @click="handleAccountClick">
            <div>My Account</div>
            <div>个人中心</div>
        </el-link>
      </nav>
      <!--知识分享模块-->
      <div class="knowledge-module" id="K_module">
        <!-- 顶部操作栏 -->
        <div class="header">
          <!-- 搜索框 -->
          <input
              type="text"
              v-model="searchKeyword"
              placeholder="标题/作者 --> 搜索Tips..."
              class="search-input"
              @keyup.enter="handleSearch"
          >
          <button class="publish-btn" @click="handleSearch">搜索</button>
          <button class="publish-btn" @click="add">发布</button>
        </div>

        <template>
          <div>
            <!-- 遮罩层 -->
            <div v-if="isAnyCardExpanded"
                 class="overlay"
                 @click="closeAllCards"></div>
            <!-- 内容卡片 -->
            <div class="cards">
              <div
                  class="card"
                  :class="{ 'active': item.expanded }"
                  v-for="item in cards"
                  :key="item.id"
                  @click.stop="toggleCard(item)"
              >
                <!--未点击时的预览内容-->
                <div class="preview" v-if="!item.expanded">
                  <img v-if="item.image" :src="item.image" class="preview-image" />
                  <div class="meta">
                    <h3 class="title">{{ item.title }}</h3>
                    <div class="info">
                      <span class="author">作者：{{ item.author }}</span>
                      <span class="time">发布时间：{{ formatTime(item.createTime) }}</span>
                    </div>
                    <div class="tags">
                      <el-tag
                          v-for="(tag, index) in item.tags"
                          :key="index"
                          :type="getRandomTagType()"
                          size="small"
                          effect="plain"
                          class="custom-tag"
                          >
                        {{ tag }}
                      </el-tag>
                    </div>
                    <p class="preview-content">{{ truncateContent(item.content) }}</p>
                  </div>
                </div>
                <!-- 展开后的详情内容 -->
                <transition name="expand">
                  <div v-if="item.expanded" class="detail">
                    <img v-if="item.image" :src="item.image" class="detail-image">
                    <div class="detail-meta">
                      <h2 class="detail-title">{{ item.title }}</h2>
                      <div class="infoe">
                        <span class="detail-author">作者：{{ item.author }}</span>
                        <span class="detail-time">发布时间：{{ formatTime(item.createTime) }}</span>
                      </div>
                      <div class="tags">
                        <el-tag
                            v-for="(tag, index) in item.tags"
                            :key="index"
                            :type="getRandomTagType()"
                            size="small"
                            effect="plain"
                            class="custom-tag"
                        >
                          {{ tag }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="detail-content">{{ item.content }}</div>
                  </div>
                </transition>
              </div>
            </div>
          </div>
        </template>
      </div>
      <transition name="fade">
        <div
            v-show="isShowBackTop"
            class="back-top"
            @click="scrollToTop"
        >
          ↑
        </div>
      </transition>
      <el-dialog title="Tip , 我也有"
                 :visible.sync="centerDialogVisible"
                 width="30%"
                 center>
        <el-form ref="form" :rules="rules" :model="form">
          <el-form-item label="标题" >
            <el-input v-model="form.title" placeholder="请输入标题" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="发布人" >
            <el-input v-model="form.publisherNo" autocomplete="off" readonly>
              <template #prefix>
                <i class="el-icon-lock" style="color: #909399"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="类型标签" prop="types">
            <el-checkbox-group
                v-model="checkedTypes"
                :min="1"
                :max="3">
              <el-checkbox
                  v-for="option in typeOptions"
                  :label="option.value"
                  :key="option.value"
              >
                {{ option.label}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-upload
              :auto-upload="false"
              :on-change="handleFileChange"
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传配图(可选)</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
          </el-upload>
          <el-form-item label="主要内容" >
            <el-input
                type="textarea"
                :autosize="{ minRows: 2}"
                placeholder="请输入内容"
                v-model="form.content"
                autocomplete="off">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button @click="submitForm" type="primary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  pointer-events: auto;
}
.container {
  width: 100%;
  margin: 0 auto;
  display: block;
  align-items: center;
}

.logo {
  font-size: 10pt;
  font-weight: bold;
  color: #F5F5F5 ;
}
.nav{
  display: block;
  padding-left: 0;
  margin-bottom: 0;
  list-style: none;
}
.nav a {
  color: #8D6E63;
  text-decoration: none;
  margin: 0 1rem;

}
.nav_font {
  color: #FAFAFA;
}

.bg-purple {
  background: #81C784 ;
}
.bg-purple-light {
  background: #81C784 ;
}

.grid-content {
  border-radius: 6px;
  min-height: 36px;
  text-align: right;
  font-size: 15pt;;
}
.grid-content1 {
  border-radius: 4px;
  min-height: 36px;
  text-align: center;

}
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.carousel-container {
  width: 95%;
  height: 77.48vh;
  max-width: 1200px; /* 最大宽度限制 */
  margin: 0 auto; /* 居中 */
  position: relative;
}
.el-carousel__container{
  position: relative;
  height: 600px;
}

.el-carousel-item {
  height: 100%; /* 关键：轮播项高度继承 */
}
.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

/*
.carousel-caption {
  position: absolute;
  margin-right: 700px;;
  bottom: 20px;
  left: 20px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px;
  border-radius: 5px;
}
*/

.knowledge-module {
  max-width: 1210px;
  margin: 5px auto;
  padding: 5px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 70%;
  max-width: 700px;
}

.publish-btn {
  margin-left: 10px;
  margin-bottom: 5px;
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 卡片样式 */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
  padding: 20px;
}

.card {
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 10px;
}
.preview {
  padding: 16px;
}
.card-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  background: #f5f5f5; /* 加载时的背景色 */
  border-radius: 8px 8px 0 0;
}
.meta {
  margin-top: 10px;
}
.preview-content {
  color: #555;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 10px 0;
}
/* 点击后的完整内容样式 */
.detail {
  padding: 16px;
  background: #fff;
  max-height: 60vh; /* 限制最大高度 */
  overflow-y: auto; /* 垂直滚动 */
}
/*激活状态*/
.card.active {
  position: fixed;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) scale(1.05) !important;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  z-index: 1000;
  width: 85%;
  max-width: 1000px;
  max-height: 80vh;
  margin: 0 !important;
  pointer-events: auto; /* 允许交互 */
  will-change: transform; /* 优化性能 */
}
/*展开动画*/
.expand-enter-active,
.expand-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.expand-enter,
.expand-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}
.card h3 {
  color: #333;
  margin: 0 0 10px;
}

.author {
  color: #666;
  font-size: 0.9em;
  margin: 0 0 10px;
}

.content {
  color: #444;
  line-height: 1.8;
  white-space: pre-wrap; /* 保留换行符 */
  padding: 10px 0;
  margin: 0 0 15px;
}
/* 标签样式优化 */
.tags {
  margin: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 标签间距 */
}
.el-tag {
  border-radius: 12px;
  padding: 4px 12px;
  font-size: 12px;
  background-color: #f0f4ff; /* 浅蓝色背景 */
  color: #4066e0; /* 深蓝色文字 */
  border: 1px solid #d6e0ff;
}
.custom-tag {
  height: 26px !important; /* 增加高度 */
  padding: 0 10px !important; /* 增加横向内边距 */
  display: flex !important;
  align-items: center !important; /* 文字垂直居中 */
  font-size: 13px !important; /* 字体稍大 */
}
.info {
  display: table;
  gap: 10px; /* 增加间距 */
  margin: 8px 0;
}
.infoe {
  display: inline-grid;
  gap: 10px; /* 增加间距 */
  margin: 8px 0;
}
.author::after {
  content: "";
  margin: 0 5px;
  color: #909399;
}

.like-btn, .comment-btn {
  padding: 8px 15px;
  border-radius: 20px;
  transition: all 0.3s;
}
.like-btn.liked {
  background-color: #ff4d4d !important;
  color: white !important;
}

.actions button {
  padding: 6px 12px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.back-top {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #42b983;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  transition: all 0.3s;
}

.back-top:hover {
  background: #35a371;
  transform: scale(1.1);
}
.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

/* 图片样式 */
.preview-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
}
.detail-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  margin-bottom: 20px;
}
/* 时间显示 */
.time, .detail-time {
  color: #909399;
  font-size: 12px;
}
/* 内容区域 */
.detail-content {
  white-space: pre-wrap;
  line-height: 1.8;
  padding: 15px 0;
  text-align: left;
  text-indent: 2em;  /* 段落首行缩进 */
  border-top: 1px solid #eee;
  margin-top: 15px;
}
/*操作按钮*/
.detail-actions {
  display: flex;
  gap: 20px;
  padding: 15px 0;
  border-top: 1px solid #eee;
}
.badge {
  cursor: pointer;
  font-size: 18px;
  color: #666;
  transition: color 0.3s;
}
.badge:hover {
  color: #409EFF;
}
.el-badge__content {
  top: 10px !important;
  right: 10px !important;
}
</style>